package com.dennytech.tac.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;

public class SearchBarEditText extends EditText implements TextWatcher {

	public SearchBarEditText(Context context) {
		super(context);
	}

	public SearchBarEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	private static final int CMD_CHANGED = 1;
	private static final long DEALY = 500;

	private Handler mDelayHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == CMD_CHANGED) {
				String keyword = (String) msg.obj;
				if (mListener != null) {
					mListener.onKeywordChanged(keyword);
				}
			}
		}

	};

	private void publishKeywordChange(String keyword) {
		mDelayHandler.removeMessages(CMD_CHANGED);
		mDelayHandler.sendMessageDelayed(
				mDelayHandler.obtainMessage(CMD_CHANGED, keyword), DEALY);
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (getVisibility() == View.GONE) {
			return;
		}
		publishKeywordChange(s.toString());
	}

	public interface OnKeywordChangeListner {
		void onKeywordChanged(String keyword);
	}

	private OnKeywordChangeListner mListener;

	public void setOnKeywordChangeListner(OnKeywordChangeListner l) {
		mListener = l;
		addTextChangedListener(this);
	}

}
